package mq;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import bean.remote.SolicitudArticuloRemote;
import dominio.SolicitudArticulo;

@MessageDriven(mappedName = "jms/queue/solicitud", activationConfig = {
		@ActivationConfigProperty(propertyName = "clientId", propertyValue = "despachoClientID"),
		@ActivationConfigProperty(propertyName = "destination", propertyValue = "jms/queue/solicitud"),
		@ActivationConfigProperty(propertyName = "user", propertyValue = "test1"),
		@ActivationConfigProperty(propertyName = "password", propertyValue = "test12341"),
		@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
		@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
public class DespachoMQListener implements MessageListener {

	@EJB(name = "solicitudArticuloBean")
	private SolicitudArticuloRemote solicitudArticuloRemote;

	@Override
	public void onMessage(Message message) {
		try {
			if (message == null) {
				throw new RuntimeException("El mensaje llego vacio");
			}

			if (message instanceof TextMessage) {
				TextMessage textMessage = (TextMessage) message;
				String text = textMessage.getText();

				InputStream articuloXml = new ByteArrayInputStream(
						text.getBytes());

				SolicitudArticulo solicitudArticulo = SolicitudArticulo
						.leer(articuloXml);

				solicitudArticuloRemote.cargar(solicitudArticulo);

				System.out.println("Recibido Mensaje Desde despacho MQ TEST: "
						+ text);
			}
		} catch (RuntimeException e) {
			e.printStackTrace();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
